<!-- 设备管理-设备运行-操作计划新增页面 -->
<template>
  <div v-if="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin: 16px 0 -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <px-form ref="formRef" :model="formValue" :rules="rules" label-position="right" label-width="120px">
        <EditDropDown dropdownTitle="设备信息">
          <template v-slot:content>
            <px-row>
              <px-col :span="12">
                <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
              </px-col>
              <px-col :span="12">
                <EquipSystemTree
                  :isRequired="true"
                  :className="formValue.className"
                  :systemCode="formValue.systemCode"
                  :currentType="props.drawerType"
                  @changeAllSystemCodes="changeAllSystemCodes"
                  @changeSystemCodes="changeSystemCodes"
                  @clearSystem="clearSystem"
                  @getEditSystemCodes="getEditSystemCodes"
                />
              </px-col>
              <px-col :span="12">
                <EquipCategorySelect
                  :isRequired="true"
                  :className="formValue.className"
                  :systemCodes="systemCodes"
                  :categoryId="formValue.categoryId"
                  @changeCategory="changeCategory"
                />
              </px-col>
              <px-col :span="12">
                <EquipTypeSelect
                  :isRequired="true"
                  :className="formValue.className"
                  :systemCodes="systemCodes"
                  :categoryId="formValue.categoryId"
                  :typeId="formValue.typeId"
                  @changeType="changeType"
                />
              </px-col>
              <px-col :span="12">
                <EquipModelSelect
                  :isRequired="true"
                  :className="formValue.className"
                  :systemCodes="systemCodes"
                  :categoryId="formValue.categoryId"
                  :typeId="formValue.typeId"
                  :modelId="formValue.modelId"
                  @changeModel="changeModel"
                />
              </px-col>
              <px-col v-if="props.drawerType === 'edit' || props.drawerType === 'copy'" :span="12">
                <px-form-item label="设备编号" prop="eqpId">
                  <px-input
                    v-model="formValue.eqpId"
                    placeholder="请点击选择"
                    maxlength="50"
                    disabled
                    style="width: calc(100% - 108px); margin-right: 8px"
                  />
                  <px-button type="primary" plain style="width: 100px" @click="dialogVisible = true">选择设备</px-button>
                </px-form-item>
              </px-col>
              <px-col v-if="props.drawerType === 'add'" :span="24">
                <px-form-item label="设备编号" prop="eqpId">
                  <px-button type="primary" plain style="width: 100px; margin-bottom: 8px" @click="multipleDialogVisible = true">选择设备</px-button>
                  <px-table v-if="props.drawerType === 'add'" :data="formValue.eqpIdList" class="equip-table" size="small" max-height="400" border>
                    <px-table-column prop="eqpId" label="设备编号" min-width="160" show-overflow-tooltip />
                    <px-table-column prop="eqpName" label="设备名称" min-width="160" show-overflow-tooltip />
                    <px-table-column fixed="right" label="操作" min-width="60" align="center">
                      <template #default="scope">
                        <px-tooltip content="删除" placement="top">
                          <px-button link type="primary" icon="Delete" @click="handleDelete(scope.$index)" />
                        </px-tooltip>
                      </template>
                    </px-table-column>
                  </px-table>
                </px-form-item>
              </px-col>
              <px-col v-if="props.drawerType === 'edit' || props.drawerType === 'copy'" :span="12">
                <px-form-item label="设备名称" prop="eqpName">
                  <px-input v-model="formValue.eqpName" placeholder="选择设备编号后自动带出" maxlength="50" disabled />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="设备运行计划">
          <template v-slot:content>
            <px-row style="width: 100%">
              <px-col :span="12">
                <px-form-item label="状态原因" prop="downCauseCode">
                  <px-select v-model="formValue.downCauseCode" placeholder="请选择状态原因" filterable clearable @change="handleStatusChange">
                    <px-option v-for="item in downCauseCodeList" :key="item.id" :label="item.name" :value="item.code" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="状态类型" prop="downTypeName">
                  <px-input v-model="formValue.downTypeName" placeholder="选择状态原因后自动带出" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col v-if="drawerType === 'add'" :span="12">
                <px-form-item label="计划开始日期" prop="startDate">
                  <px-date-picker
                    v-model="formValue.startDate"
                    style="width: 70%"
                    placeholder="请选择计划开始日期"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :clearable="false"
                    :disabled-date="disabledDate"
                    @change="changeStartDateTime"
                  />
                  <px-time-select
                    v-model="startDateTime"
                    style="width: 30%"
                    placeholder="请选择计划开始时间"
                    start="00:00"
                    step="00:15"
                    end="23:45"
                    format="HH:mm"
                    :clearable="false"
                    @change="changeStartDateTime"
                  />
                </px-form-item>
              </px-col>
              <px-col v-if="drawerType !== 'add'" :span="12">
                <px-form-item label="计划开始时间" prop="startTime">
                  <px-date-picker
                    v-model="formValue.startTime"
                    placeholder="请选择计划开始时间"
                    type="datetime"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :clearable="false"
                    :disabled-date="disabledDate"
                    @change="changeStartTime"
                  />
                  <!-- :disabled-hours="disabledHours"
                    :disabled-minutes="disabledMinutes"
                    :disabled-seconds="disabledSeconds" -->
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
      </px-form>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </div>
  <!-- 选择设备弹窗-单选 -->
  <EquipIdSelectDialog
    :visible="dialogVisible"
    :className="formValue.className"
    :systemCodes="systemCodes"
    :categoryId="formValue.categoryId"
    :typeId="formValue.typeId"
    :modelId="formValue.modelId"
    @closeEquipDialog="closeEquipDialog"
    @changeEqpId="changeEqpId"
  />
  <!-- 选择设备弹窗-多选 -->
  <EquipIdMultipleSelectDialog
    :dialogVisible="multipleDialogVisible"
    :className="formValue.className"
    :systemCodes="systemCodes"
    :categoryId="formValue.categoryId"
    :typeId="formValue.typeId"
    :modelId="formValue.modelId"
    @closeEquipDialog="closeMultipleEquipDialog"
    @changeEqpIds="changeMultipleEqpId"
  />
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, watch, computed } from "vue";
import { PxMessage, PxMessageBox } from "px-ui";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import EquipCategorySelect from "@/views/all/equip/components/EquipCategorySelect.vue";
import EquipTypeSelect from "@/views/all/equip/components/EquipTypeSelect.vue";
import EquipModelSelect from "@/views/all/equip/components/EquipModelSelect.vue";
import EquipIdSelectDialog from "@/views/all/equip/components/EquipIdSelectDialog.vue";
import { addRunOperatePlan, getRunStatusReasonSelect } from "@/api/equip/runManage";
import { formatDuration } from "@/utils/pengxi";
import EquipIdMultipleSelectDialog from "@/views/all/equip/components/EquipIdMultipleSelectDialog.vue";
import { cloneDeep, isEqual } from "@pureadmin/utils";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "drawerType", "rowData"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);

// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {
    className: "",
    systemCode: "",
    categoryId: null,
    typeId: null,
    modelId: null,
    eqpId: "",
    eqpName: "",
    eqpIdList: []
  },
  downCauseCodeList: [], // 状态原因列表
  startDateTime: "14:00", // 默认开始时间
  isDisabled: false, // 禁用-自动上报不允许编辑设备信息，手动上报可以编辑设备信息
  systemCodes: [],
  dialogVisible: false,
  multipleDialogVisible: false,
  differContent: null
});
const { formValue, downCauseCodeList, startDateTime, isDisabled, systemCodes, dialogVisible, multipleDialogVisible, differContent } = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  eqpId: [{ required: true, message: "设备编号不能为空", trigger: "blur" }],
  startTime: [{ required: true, message: "状态开始时间不能为空", trigger: "change" }],
  downCauseCode: [{ required: true, message: "状态原因不能为空", trigger: "blur" }],
  startDate: [{ required: true, message: "状态开始日期不能为空", trigger: "change" }]
}));

// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    isDisabled.value = false;
    formRef.value?.resetFields();
    systemCodes.value = [];
    downCauseCodeList.value = await getRunStatusReasonSelect({});
    if (props.drawerType === "add") {
      formValue.value = {
        className: "",
        systemCode: "",
        categoryId: null,
        typeId: null,
        modelId: null,
        eqpId: "",
        eqpName: "",
        eqpIdList: []
      };
      formValue.value.startDate = "";
      startDateTime.value = "14:00";
    } else if (props.drawerType === "edit") {
      const rowData = JSON.parse(JSON.stringify(props.rowData));
      formValue.value = rowData;
      formValue.value.eqpId = rowData.eqpId;
      const { reportType } = rowData;
      if (reportType === "AUTOMATIC_REPORT") {
        isDisabled.value = true;
      } else if (reportType === "MANUAL_REPORT") {
        isDisabled.value = false;
      }
    } else if (props.drawerType === "copy") {
      const rowData = JSON.parse(JSON.stringify(props.rowData));
      formValue.value = rowData;
      formValue.value.eqpId = rowData.eqpId;
      delete formValue.value.id;
      const { reportType } = rowData;
      if (reportType === "AUTOMATIC_REPORT") {
        isDisabled.value = true;
      } else if (reportType === "MANUAL_REPORT") {
        isDisabled.value = false;
      }
    }
    differContent.value = cloneDeep(formValue.value);
  }
});

// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (props.drawerType === "add") {
        const params = {
          eqpId: formValue.value.eqpIdList.map(obj => obj.eqpId),
          eqpIdList: formValue.value.eqpIdList.map(obj => obj.eqpId),
          eqpRunStatus: 1,
          startTime: formValue.value.startTime,
          downCauseCode: formValue.value.downCauseCode
        };
        await addRunOperatePlan(params);
        PxMessage.success("新增成功");
        formValue.value.eqpIdList = [];
        emits("backMainPage");
        emits("queryTable");
      } else if (props.drawerType === "edit") {
        const params = {
          eqpId: formValue.value.eqpId,
          id: props.rowData.id,
          eqpIdList: [formValue.value.eqpId],
          eqpRunStatus: 1,
          startTime: formValue.value.startTime,
          downCauseCode: formValue.value.downCauseCode
        };
        await addRunOperatePlan(params);
        PxMessage.success("编辑成功");
        formValue.value.eqpIdList = [];
        emits("backMainPage");
        emits("queryTable");
      } else if (props.drawerType === "copy") {
        const params = {
          eqpId: formValue.value.eqpId,
          eqpIdList: [formValue.value.eqpId],
          eqpRunStatus: 1,
          startTime: formValue.value.startTime,
          downCauseCode: formValue.value.downCauseCode
        };
        await addRunOperatePlan(params);
        PxMessage.success("新增成功");
        formValue.value.eqpIdList = [];
        emits("backMainPage");
        emits("queryTable");
      }
      formValue.value = {
        className: "",
        systemCode: "",
        categoryId: null,
        typeId: null,
        modelId: null,
        eqpId: "",
        eqpName: "",
        eqpIdList: []
      };
    }
  });
};
// 返回主页面
const backMainPage = () => {
  const differCont = cloneDeep(formValue.value);
  if (isEqual(differContent.value, differCont)) {
    formRef.value?.resetFields();
    differContent.value = null;
    emits("backMainPage");
    return;
  }
  PxMessageBox.confirm("确认退出页面？退出后内容不会保存", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      formValue.value.eqpIdList = [];
      formRef.value?.resetFields();
      differContent.value = null;
      emits("backMainPage");
    })
    .catch(() => {});
};
// 关闭子级设备dialog弹窗
const closeEquipDialog = () => {
  dialogVisible.value = false;
};
// 关闭设备多选dialog弹窗
const closeMultipleEquipDialog = () => {
  multipleDialogVisible.value = false;
};

// 禁用日期
const disabledDate = (time: Date) => {
  return time.getTime() < new Date().getTime() - 8.64e7;
};
// 禁用时
const disabledHours = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.startTime.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate <= todayDate) {
    for (let i = 0; i < 24; i++) {
      if (new Date().getHours() <= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};
// 禁用分
const disabledMinutes = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.startTime.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate <= todayDate) {
    for (let i = 0; i < 60; i++) {
      if (new Date().getMinutes() <= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};
// 禁用秒
const disabledSeconds = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.startTime.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate <= todayDate) {
    for (let i = 0; i < 60; i++) {
      if (new Date().getSeconds() <= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};
// 状态原因改变，获取状态类型
const handleStatusChange = val => {
  const arr = downCauseCodeList.value.filter(item => {
    return item.code === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.downTypeName = arr[0].downTypeName;
  }
};
// 新增时的日期时间值
const changeStartDateTime = () => {
  formValue.value.startTime = formValue.value.startDate + " " + startDateTime.value + ":00";
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  formValue.value.className = val;
  systemCodes.value = [];
  formValue.value.eqpIdList = [];
  if (!isOnlyClass) {
    formRef.value?.resetFields(["systemCode", "categoryId", "typeId", "modelId", "eqpId", "eqpName"]);
  }
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  formValue.value.className = val2;
  formValue.value.systemCode = val3;
  systemCodes.value = val4;
  formValue.value.eqpIdList = [];
  formRef.value?.resetFields(["categoryId", "typeId", "modelId", "eqpId", "eqpName"]);
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  formValue.value.systemCode = val;
  systemCodes.value = val2;
  formValue.value.eqpIdList = [];
  formRef.value?.resetFields(["categoryId", "typeId", "modelId", "eqpId", "eqpName"]);
};
// 系统组件值改变触发
const clearSystem = val => {
  systemCodes.value = [];
  formRef.value?.resetFields(["systemCode", "categoryId", "typeId", "modelId", "eqpId", "eqpName"]);
};
// 用于编辑时的页面回显，保证类型型号过滤是正确的
const getEditSystemCodes = (val, val2) => {
  formValue.value.systemCode = val;
  systemCodes.value = val2;
};
// 改变设备总称，清空设备类型和设备型号
const changeCategory = val => {
  formValue.value.categoryId = val;
  formValue.value.eqpIdList = [];
  formRef.value?.resetFields(["typeId", "modelId", "eqpId", "eqpName"]);
};
// 改变设备类型，清空设备型号
const changeType = (val, val2) => {
  formValue.value.categoryId = val2;
  formValue.value.typeId = val;
  formValue.value.eqpIdList = [];
  formRef.value?.resetFields(["modelId", "eqpId", "eqpName"]);
};
// 改变设备型号
const changeModel = (val, val2, val3) => {
  formValue.value.categoryId = val2;
  formValue.value.typeId = val3;
  formValue.value.modelId = val;
  formValue.value.eqpIdList = [];
  formRef.value?.resetFields(["eqpId", "eqpName"]);
};
// 改变设备编号
const changeEqpId = equipDetail => {
  formValue.value.className = equipDetail?.className || "";
  formValue.value.systemCode = equipDetail?.systemCode || "";
  systemCodes.value = [];
  formValue.value.categoryId = equipDetail?.categoryId || "";
  formValue.value.typeId = equipDetail?.typeId || "";
  formValue.value.modelId = equipDetail?.modelId || "";
  formValue.value.eqpId = equipDetail?.eqpId || "";
  formValue.value.eqpIdList = [equipDetail?.eqpId] || [];
  formValue.value.eqpName = equipDetail?.eqpName || "";
};
//选择多个设备
const changeMultipleEqpId = val => {
  if (val) {
    formValue.value.eqpIdList = formValue.value.eqpIdList?.concat(val)?.filter((obj, index, self) => {
      return self.map(x => x.eqpId).indexOf(obj.eqpId) === index;
    });
  }
  formValue.value.eqpId = formValue.value.eqpIdList.map(obj => obj.eqpId);
};
//删除设备某一项
const handleDelete = index => {
  formValue.value.eqpIdList?.splice(index, 1);
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
